package dao

import (
	"errors"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"mychat/internal/conf"
	"mychat/internal/data/dao/model"
)

func CreateAndInitMysqlDb(msc *conf.Mysql) (*gorm.DB, error) {
	db, err := gorm.Open(mysql.Open(msc.Dsn), &gorm.Config{})
	if err != nil {
		return nil, err
	}

	sqlDB, err := db.DB()
	if err != nil {
		return nil, errors.New("failed to get sql DB instance")
	}

	sqlDB.SetMaxOpenConns(msc.MaxOpenConns)
	sqlDB.SetMaxIdleConns(msc.MaxIdleConns)
	sqlDB.SetConnMaxLifetime(msc.ConnMaxLifeTime)

	if msc.AutoMigrate {
		err = db.AutoMigrate(&model.User{})
		if err != nil {
			return nil, err
		}

		err = db.AutoMigrate(&model.UserFreind{})
		if err != nil {
			return nil, err
		}
	}

	return db, nil
}
